package com.boco.pciv.controller.builder;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.boco.pciv.SysProperties;
import com.boco.pciv.controller.PcivController;
import com.boco.pciv.controller.company.CompanyController;
import com.boco.pciv.core.entity.*;
import com.boco.pciv.core.exception.PcivException;
import com.boco.pciv.core.security.LoginUser;
import com.boco.pciv.entity.builder.BuilderInfo;
import com.boco.pciv.entity.builder.ProComBuildInfo;
import com.boco.pciv.entity.builder.ProComRes;
import com.boco.pciv.entity.sys.UserLogInfo;
import com.boco.pciv.service.builder.IBuilderService;
import com.boco.pciv.service.sys.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value="/builder/")
public class builderController extends PcivController {
    Logger logger = LoggerFactory.getLogger(CompanyController.class);

    @Resource
    private IUserService iUserService;
    @Resource
    private IBuilderService iBuilderService;
    @Autowired
    SysProperties sysConfig;

    @GetMapping("/list")
    public PageResultBase getList(String name, LayUIPager pageParam) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pageParam);
        param.putCriteria("name", name);
        PageResultBase result = iBuilderService.getPage(param);
        addOperationLog("查询", sysConfig.getBuilderName()+"查询");
        return result;
    }

    @GetMapping("/proBulidComList")
    public PageResultBase geProBulidComList(String projectName, String builderName,String companyName,LayUIPager pageParam) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pageParam);
        param.putCriteria("projectName", projectName);
        param.putCriteria("builderName", builderName);
        param.putCriteria("companyName", companyName);
        LoginUser user=getCurUser();
        if(user.getUserType()!=0){
            param.putCriteria("UserType", user.getUserType());
            param.putCriteria("licno", user.getDeptId());
        }
        PageResultBase result = iBuilderService.geProBulidComList(param);
        addOperationLog("查询", "项目-建筑公司-劳务公司关系查询");
        return result;
    }

    @GetMapping(value="/getdd4Builder")
    public BizResponse getdd4Builder(Integer hasAll) {
        //下拉框
        List<SelectItem> list = new ArrayList<SelectItem>();
//        if (hasAll != null && hasAll == 1) {
//            list.add(new SelectItem("", "请选择", "Company"));
//        }
        List<BuilderInfo> result = iBuilderService.getAll();
        for (BuilderInfo dd : result) {
            list.add(new SelectItem(dd.getLicno(), dd.getBuilderName(), "builder"));
        }
        return BizResponseUtil.list(list);
    }

    @GetMapping("/info")
    public BizResponse getInfo(Integer id) {
        BuilderInfo result = iBuilderService.getOne(id);
        return BizResponseUtil.single(result);
    }
    @GetMapping("/companys")
    public BizResponse getcompanys(String projectId) {
        String result = iBuilderService.getprojectinfo(projectId);
        return BizResponseUtil.single(result);
    }
    @PostMapping("/add")
    public BizResponse addBuilder(BuilderInfo info) {
        if (info == null) {
            return BizResponseUtil.fail("新增信息不能为空");
        }
        try {
            String str=iBuilderService.reColoms(info);
            if(StrUtil.isNotBlank(str)) {
                return BizResponseUtil.fail(str);
            }

            String pwd = sysConfig.getCompanyDefaultPassword() + info.getPhone().substring(7, 11);
            info.setDefPwd(pwd);
            info.setCreateUser(getCurUserId());
            info.setBuilderid(sysConfig.getBuilderRoleID());
            iBuilderService.addUser(info);

            info.setCreateUser(getCurUserId());
            info.setDefPwd(pwd);
            iBuilderService.add(info);
            addOperationLog("新增", String.format("新增%s:%s",sysConfig.getBuilderName(),info.getBuilderName()));
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    @PostMapping("/edit")
    public BizResponse editCompany(BuilderInfo info) {
        try {
//            String str=iBuilderService.reColoms(info);
//            if(StrUtil.isNotBlank(str)) {
//                return BizResponseUtil.fail(str);
//            }
            BuilderInfo result = iBuilderService.getOne(info.getId());
            if (!result.getPhone().equals(info.getPhone())) {
                String pwd = sysConfig.getCompanyDefaultPassword() + info.getPhone().substring(7, 11);
                iUserService.deleteByUserId(result.getPhone());
                info.setDefPwd(pwd);
                info.setCreateUser(getCurUserId());
                info.setBuilderid(sysConfig.getBuilderRoleID());
                iBuilderService.addUser(info);
                info.setDefPwd(pwd);
            }
            info.setUpdateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            iBuilderService.edit(info);
            addOperationLog("修改", String.format("更新%s:%s",sysConfig.getBuilderName(), info.getId()));
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    @PostMapping("/deleteRes")
    public BizResponse deleteRes(int id) {
        try {
            iBuilderService.delete(id);
            addOperationLog("删除", String.format("删除项目和劳务公司对于关系:%s",id));
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    @PostMapping("/delete")
    public BizResponse deleteBuilder(Integer id, String phone,String status) {
        try {
//            iUserService.deleteByUserId(phone);
            Map<String, Object> map = new HashMap();
            map.put("id",id);
            map.put("userId",phone);
            if("del".equals(status)){
                map.put("status",1);
                map.put("state",3);
            }
            else{
                map.put("status",0);
                map.put("state",1);
            }
            iBuilderService.updateUserStatus(map);
            iBuilderService.deleteBuilder(map);
            addOperationLog("删除", String.format("删除%s:%s",sysConfig.getBuilderName(),id));
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    @PostMapping("/pwdResert")
    public BizResponse pwdResert(String phone) {
        try {
            String newpwd = sysConfig.getCompanyDefaultPassword() + phone.substring(7, 11);
            if(sysConfig.getCompanyDefaultPassword().length()!=5){
                newpwd = sysConfig.getCompanyDefaultPassword();
            }
            iUserService.modifyPassword(phone, newpwd);
            return BizResponseUtil.success(MSG_ExeOK, newpwd);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    @PostMapping("/addProComRes")
    public BizResponse addProComRes(String json) {
        try {
            ProComRes info = JSONUtil.toBean(json, ProComRes.class);
            if (info == null) {
                return BizResponseUtil.fail("新增信息不能为空");
            }
            LoginUser user=getCurUser();
            if(user.getUserType()!=2){
                return BizResponseUtil.fail(sysConfig.getBuilderName()+"账户才能进行项目分配！");
            }
            info.setBuilder_id(user.getDeptId());
            iBuilderService.addProComRes(info);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }


}
